<template>
  <view class="user-info-img">
    <image
      class="avatar"
      mode="aspectFill"
      :src="avatarUrl || img"
      @click="showAvatarUploadModal"
    ></image>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import {uploadImgApi} from '@/api/common'
import { showWarning, showSuccess, showError,showLoading } from '@/utils/feedback'

const props = defineProps({
  img: {
    type: String,
    default: "/static/images/null.png",
  },
});

const avatarUrl = ref('')

// 显示头像上传弹窗
const showAvatarUploadModal = () => {
  uni.showActionSheet({
    itemList: ["从相册选一张", "拍一张照片"],
    success: (res) => {
      if (res.tapIndex === 0) {
        chooseImageFromAlbum();
      } else if (res.tapIndex === 1) {
        takePhoto();
      }
    },
    fail: (err) => {
      console.log("取消选择");
    },
  });
};

const chooseImageFromAlbum = async () => {
  const res = await uni.chooseImage({
    count: 1,
    sizeType: ["compressed"],
    sourceType: ["album"],
  });

  if (res.errMsg === "chooseImage:ok") {
    uploadFile(res.tempFilePaths[0]);
  }
};

const takePhoto = async () => {
  const res = await uni.chooseImage({
    count: 1,
    sizeType: ["compressed"],
    sourceType: ["camera"],
  });

  if (res.errMsg === "chooseImage:ok") {
    uploadFile(res.tempFilePaths[0]);
  }
};

const uploadFile = async (filePath) => {
  const maxSize = 4 * 1024 * 1024; // 4MB
  
  try {
    // 检查文件大小
    const fileInfo = await uni.getFileInfo({ filePath });
    if (fileInfo.size > maxSize) {
      showWarning("图片大小不能超过4M")
      return;
    }

    // 显示加载中
    showLoading('上传中...');

  
    // 正式上传文件
    const res = await uploadImgApi({
      filePath,
      name: 'file', 
    });

    if (res.code == 200) {
      avatarUrl.value = res.data.url
      showSuccess(res.message);
    } else {
      showWarning(res.message);
    }
  } catch (err) {
    console.error(err)
    showError(res.message);
  } finally {
    uni.hideLoading()
  }
};
</script>

<style lang="scss" scoped>
.user-info-img {
  .avatar {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    border: 4px solid #fff;
  }
}
</style>